package org.hdax.dm.rest.service;

import org.hdax.dm.dao.entitydao.DmSchedulerDao;
import org.hdax.dm.entity.scheduler.DmScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RestController
public class RestSchedulerService {

    @Autowired
    private DmSchedulerDao dmSchedulerDao;

    @PostMapping(path = "/findByDmScheduler")
    public List<DmScheduler> findByDmScheduler(@RequestBody DmScheduler dmScheduler) {
        return dmSchedulerDao.findAll(where(dmScheduler));
    }

    public Specification<DmScheduler> where(DmScheduler dmScheduler) {
        return new Specification<DmScheduler>() {
            @Override
            public Predicate toPredicate(Root<DmScheduler> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (dmScheduler != null) {
                    if (dmScheduler.getItemId() != null && dmScheduler.getItemId() > 0) {
                        predicateList.add(criteriaBuilder.equal(root.get("itemId").as(Integer.class), dmScheduler.getItemId()));
                    }
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
            }
        };
    }
}
